<template>
  <el-drawer
    v-model="showDrawer"
    :title="$t('创建挂单')"
    size="35%"
    @close="emit('close')"
  >
    <el-card v-loading="loading">
      <el-form
        ref="createFormRef"
        label-position="top"
        :model="createForm"
        :rules="rules"
      >
        <el-form-item prop="coinName" :label="$t('选择货币')">
          <el-select
            style="width: 100%"
            v-model="createForm.coinName"
            :placeholder="$t('请选择币种')"
            @change="changeCoin"
          >
            <el-option
              v-for="item in coins"
              :key="item.coin_name"
              :label="item.coin_name"
              :value="item.coin_name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="quantity"
          :label="$t('设置订单金额')"
          style="position: relative"
        >
          <span style="position: absolute; top: -100%; right: 0">余额 : 0</span>
          <el-input
            v-model="createForm.quantity"
            type="number"
            :placeholder="$t('请输入订单金额')"
          ></el-input>
        </el-form-item>
        <el-form-item prop="tradingRange" :label="$t('设置单笔交易区间额度')">
          <div class="tradingRangeRow">
            <el-input type="number"
              v-model="createForm.tradingRange[0]"
              :placeholder="$t('最小额度')"
            ></el-input>
            <span style="padding: 0 5px"> —— </span>
            <el-input type="number"
              v-model="createForm.tradingRange[1]"
              :placeholder="$t('最大额度')"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item prop="feeRatio" :label="$t('设置手续费')">
          <el-input type="number"
            v-model="createForm.feeRatio"
            :placeholder="$t('请输入比率')"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            style="width: 100%"
            size="large"
            type="primary"
            :disabled="!isClickConfirmBtn"
            @click="confirmForm(createFormRef)"
          >
            {{ $t("提交") }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-drawer>
</template>
<script setup>
import { ref, reactive, watch, computed } from "vue";
import {
  getSwapMarketDetailApi,
  getSwapCoinsApi,
  postSwapPublishApi,
} from "@/api/swap/index";
import { useI18n } from "vue-i18n";
import _ from "lodash";
import { dayjs } from "element-plus";
import { useStatusStore } from "@/store/modules/status";
const { t } = useI18n();
const statusStore = useStatusStore();
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  coinList: {
    type: Array,
    default: () => [],
  },
  recordId: {
    type: String,
    default: "",
  },
});
const emit = defineEmits(["close"]);
const loading = ref(false);
const showDrawer = ref(false);
watch(
  () => props.show,
  (val) => {
    showDrawer.value = val;
  }
);
watch(
  () => props.recordId,
  (val) => {
    if (val) {
      getPendingOrderDetail();
      createForm.record_id = val;
    }
  },
  { immediate: true }
);
const createFormRef = ref();
const createForm = reactive({
  coinName: "",
  quantity: "",
  tradingRange: ["", ""],
  feeRatio: "",
});
const isClickConfirmBtn = computed(() => {
  let isOk = true;
  if (Object.values(createForm).some((value) => !value)) {
    isOk = false;
  }
  return isOk;
});
const checkTradingRange = (rule, value, callback) => {
  if (!value[0]) {
    callback(new Error(t("请输入最小额度")));
  } else if (!value[1]) {
    callback(new Error(t("请输入最大额度")));
  } else if (value[1] > createForm.quantity) {
    callback(new Error(t("最大额度不能大于订单金额")));
  } else if (value[0] > value[1]) {
    callback(new Error(t("请输入正确的最大额度")));
  } else {
    callback();
  }
};
const rules = reactive({
  coinName: [{ required: true, message: t("请选择币种"), trigger: "change" }],
  quantity: [{ required: true, message: t("请输入数量"), trigger: "change" }],
  tradingRange: [
    { required: true, validator: checkTradingRange, trigger: "blur" },
  ],
  feeRatio: [{ required: true, message: t("请输入手续费"), trigger: "change" }],
});

const coins = ref([]);
watch(
  () => props.coinList,
  (newVal) => {
    if (newVal.length) {
      coins.value = newVal;
    }
  },
  { immediate: true }
);
const getPendingOrderDetail = async () => {
  try {
    loading.value = true;
    const res = await getSwapMarketDetailApi({
      record_id: props.recordId,
    });
    if (res) {
      createForm.coinName = res.coin_name;
      createForm.quantity = res.quantity;
      createForm.tradingRange = [res.min_quantity, res.max_quantity];
      createForm.feeRatio = res.fee_ratio;
    }
    loading.value = false;
  } catch (e) {
    loading.value = false;
    console.log(e);
  }
};

const changeCoin = () => {};

const form = computed(() => {
  let obj = {
    coin_name: createForm.coinName,
    quantity: createForm.quantity,
    min_quantity: createForm.tradingRange[0],
    max_quantity: createForm.tradingRange[1],
    fee_ratio: createForm.feeRatio,
  };
  if (createForm.record_id) {
    obj.record_id = createForm.record_id;
  }
  return obj;
});
const confirmForm = (formRef) => {
  if (!formRef) return;
  formRef.validate(async (valid, fields) => {
    if (valid) {
      console.log("submit!");
      loading.value = true;
      const { record_id } = await postSwapPublishApi(form.value);
      emit("close", record_id || createForm.record_id || "");
      for (const item in createForm) {
        createForm[item] = "";
      }
      loading.value = false;
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>
<style lang="scss">
.tradingRangeRow {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;

  // .rowName {
  //   min-width: 30%;
  //   flex-shrink: 0;
  //   display: flex;
  //   align-items: center;
  // }

  // .rowValue {
  //   word-break: break-all;
  //   text-align: right;
  // }
}
</style>
